<?php
class Timezone extends Plugin {
	function info() {
		return array(
			'url'				=> 'http://www.shihui.org/sheng/timezone-plugin-for-habari',
			'name'				=> 'TimeZone Selector Plugin',
			'description'			=> 'Select the timezone and make date be correct in your timezone',
			'license'			=> 'Apache License 2.0',
			'author'			=> 'Mike Shi',
			'authorurl'			=> 'http://www.shihui.org/sheng/',
			'version'			=> '0.8'
		);
	}

	public function action_plugin_activation($file) {
		if (strlen(self::getvar('timezone')) == 0) {
			$timezone_identifiers = timezone_identifiers_list();
			$index = array_search(date_default_timezone_get(), $timezone_identifiers);
			Options::set('timezone:timezone',$index);
		}
	}

        public function filter_plugin_config($actions, $plugin_id) {
                if ($plugin_id == $this->plugin_id()) {
                        $actions[] = _t('Configure');
                }
                return $actions;
        }

        public function action_plugin_ui($plugin_id, $action) {
                if ($plugin_id == $this->plugin_id()) {
                        switch ($action) {
                                case _t('Configure'):
                                        $ui = new FormUI(strtolower(get_class($this)));
					$timezone_identifiers = timezone_identifiers_list();
                                        $timezone= $ui->add('select', 'timezone', _t('Timezone'));
					$timezone->options = $timezone_identifiers;
                                        $ui->on_success(array($this, 'updated_config'));
                                        $ui->out();
                                break;
                        }
                }
        }

        public function updated_config($ui) {
                return true;
        }

        private static function getvar($var) {
                return Options::get('timezone:'.$var);
        }

	public function filter_post_pubdate($out, $post) {
		$timezone_identifiers = timezone_identifiers_list();
		$tz = new DateTimeZone($timezone_identifiers[self::getvar('timezone')]);
		$tm = new DateTime($out);
		$tm->setTimezone($tz);
		return $tm->format('Y-m-d H:i:s');
	}

	public function action_post_update_pubdate($post, $oldvalue, $newvalue) {
		$timezone_identifiers = timezone_identifiers_list();
		$user_tz = new DateTimeZone($timezone_identifiers[self::getvar('timezone')]);
		$origin_tz = new DateTimeZone(date_default_timezone_get());
		$tm = new DateTime($oldvalue, $user_tz);
		$tm->setTimezone($origin_tz);
		$post->pubdate = $tm->format('Y-m-d H:i:s');
	}
}
?>

